import 'dart:convert';

import 'package:inmotion_pro/http/area_helper.dart';
import 'package:inmotion_pro/pages/login_register/area_code/country_model.dart';
import 'package:inmotion_pro/pages/models/firmware_info_model.dart';
import 'package:inmotion_pro/pages/models/http_response/http_response_model.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import '../custom_exception/api_exception.dart';
import '../pages/models/http_response/firmware_info_response_model.dart';
import 'api_interceptor.dart';

// Api助手
class ApiHelper {
  // 单例模式
  static final ApiHelper _instance = ApiHelper._();

  // 获取单例实例
  factory ApiHelper() => _instance;

  // 私有构造函数
  ApiHelper._() {
    setBaseUrlUserByArea(AreaHelper.httpArea);
  }

  // http请求管理器
  final HttpManager httpManager = HttpManager();

  // http api拦截器
  final ApiInterceptor apiInterceptor = ApiInterceptor();

  // 设置基础url
  void setBaseUrlUserByArea(String area) {
    httpManager.baseUrl = "https://api.$area.imscv.com";
    AreaHelper.saveHttpArea(area);
    // 插入自定义错误拦截器
    httpManager.dioInterceptor = apiInterceptor;
  }

  // 获取基础参数
  baseGetMap() {
    Map<String, dynamic> map = {};
    map["timestamp"] = DateTime.now().millisecondsSinceEpoch;
    return map;
  }

  // MARK: - 获取国家/地区列表
  Future<List<AreaCodeModel>> getCountryList() {
    return httpManager
        .request<AreaCodeModel>(
            RequestType.GET, "/v2/regions", AreaCodeModel.fromJson)
        .then((response) {
      if (!response.isSuccess || response.listData == null) {
        throw ApiException(response.code, response.message);
      }
      return response.listData!;
    });
  }

  // MARK: - 获取用户所属地区
  Future<String> getUserRegion() {
    return httpManager.request<HttpResponseModel>(
      RequestType.GET,
      "/v2/region/get",
      HttpResponseModel.fromJson,
      queryParameters: {
        ...baseGetMap(),
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      return response.data != null ? response.data!.area : "";
    });
  }

  // MARK: - 设置用户所属地区
  Future<bool> setUserRegion(String region) {
    return httpManager.request<HttpResponseModel>(
      RequestType.GET,
      "/v2/region/set",
      HttpResponseModel.fromJson,
      queryParameters: {
        "region": region,
      },
    ).then((response) {
      if (!response.isSuccess) {
        throw ApiException(response.code, response.message);
      }
      return response.isSuccess;
    });
  }

  // MARK: - 根据IP的逆地理编码,判断用户所属地区是否中国
  Future<String> getIpGeo() {
    return httpManager.request<HttpResponseModel>(
      RequestType.GET,
      "/v2/ip-geo",
      HttpResponseModel.fromJson,
      queryParameters: {
        ...baseGetMap(),
      },
    ).then((response) {
      if (!response.isSuccess || response.data == null) {
        throw ApiException(response.code, response.message);
      }
      return response.data!.phoneCode;
    });
  }

  // MARK: - 检查固件更新
  Future<FirmwareUpgradeRspModel> checkFirmwareUpgrade(
    String sn,
    String productModel,
    List<FirmwareInfoModel> firmwareInfoList,
  ) {
    List<Map<String, String>> list = firmwareInfoList
        .map((e) => {
              "appVersion": e.appVersion,
              "blVersion": e.bootVersion,
              "hwVersion": e.hwVersion,
              "device": e.deviceId.toString(),
            })
        .toList();

    return httpManager.request<FirmwareUpgradeRspModel>(
      RequestType.GET,
      "/v1/product/firmware/latest",
      FirmwareUpgradeRspModel.fromJson,
      queryParameters: {
        "sn": sn,
        "model": productModel,
        "version": jsonEncode(list),
        ...baseGetMap(),
      },
    ).then(
      (response) {
        if (!response.isSuccess) {
          throw ApiException(response.code, response.message);
        }
        return response.data ?? FirmwareUpgradeRspModel.fromJson({});
      },
    );
  }

  // MARK: - 产品手册数据
  Future<List<Map<String, dynamic>>> getProductManualData(int type) {
    return httpManager.request<HttpResponseModel>(
      RequestType.GET,
      "/v2/manuals",
      HttpResponseModel.fromJson,
      queryParameters: {
        "type": type,
        ...baseGetMap(),
      },
    ).then((response) {
      if (!response.isSuccess || response.listData == null) {
        throw ApiException(response.code, response.message);
      }
      return response.listData!.map((e) => e.originData).toList();
    });
  }

  // MARK: - 视频指南数据
  Future<List<Map<String, dynamic>>> getVideoGuideData(int type) {
    return httpManager.request<HttpResponseModel>(
      RequestType.GET,
      "/v2/videos",
      HttpResponseModel.fromJson,
      queryParameters: {
        "type": type,
        ...baseGetMap(),
      },
    ).then((response) {
      if (!response.isSuccess || response.listData == null) {
        throw ApiException(response.code, response.message);
      }
      return response.listData!.map((e) => e.originData).toList();
    });
  }
}
